package com.szpxt.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

import com.szpxt.model.Organization;

@Component
public class OrganizationService extends HibernateDaoSupport {

	public List<Organization> getRoot() {
		DetachedCriteria criteria = DetachedCriteria.forClass(Organization.class);
		criteria.add(Restrictions.isNull("parent"));
		
		return (List<Organization>)getHibernateTemplate().findByCriteria(criteria);
	}
	
	public Organization saveOrUpdate(Map<String, String> map) {
		String id = map.get("id");					//获取属性
		String name = map.get("name");
		String parentId = map.get("parentId");
		
		Organization organization = new Organization();
		if(!StringUtils.isBlank(id)) {							//是否修改
			organization = get(Long.parseLong(id));
		}
		Organization organizationParent = get(Long.parseLong(parentId));
		
		organization.setName(name);					//设置属性
		organization.setParent(organizationParent);
		
		getHibernateTemplate().saveOrUpdate(organization);			//保存实体
		
		return organization;
	}
	
	public Organization get(long id) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Organization.class);
		criteria.add(Restrictions.eq("id", id));
		
		return (Organization)getHibernateTemplate().findByCriteria(criteria).get(0);
	}
	
	public void delete(long id) {
		Organization organization = get(id);
		getHibernateTemplate().delete(organization);
	}
	
	public void saveOrUpdate(Organization organization) {
		getHibernateTemplate().saveOrUpdate(organization);
	}
}
